package com.macro.mall.service.impl;

import com.macro.mall.mapper.XhsUserMapper;
import com.macro.mall.model.XhsUser;
import com.macro.mall.service.XhsUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class XhsUserServiceImpl implements XhsUserService {

    @Autowired
    private XhsUserMapper xhsUserMapper;

    @Override
    public int create(XhsUser user) {
        return xhsUserMapper.insert(user);
    }

    @Override
    public int update(XhsUser user) {
        return xhsUserMapper.updateByPrimaryKey(user);
    }

    @Override
    public XhsUser getById(Long id) {
        return xhsUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public XhsUser getByOpenId(String openId) {
        return xhsUserMapper.selectByOpenId(openId);
    }

    @Override
    public XhsUser getByPhoneNumber(String phoneNumber) {
        return xhsUserMapper.selectByPhoneNumber(phoneNumber);
    }

    @Override
    public List<XhsUser> listAll() {
        return xhsUserMapper.selectAll();
    }

    @Override
    public int delete(Long id) {
        return xhsUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public XhsUser createOrUpdatePhoneInfo(String openId, String phoneNumber,
                                         String purePhoneNumber, String countryCode) {
        XhsUser user = xhsUserMapper.selectByOpenId(openId);
        if (user == null) {
            // 创建新用户
            user = new XhsUser();
            user.setOpenId(openId);
            user.setPhoneNumber(phoneNumber);
            user.setPurePhoneNumber(purePhoneNumber);
            user.setCountryCode(countryCode);
            xhsUserMapper.insert(user);
            log.info("创建新小红书用户: openId={}, phone={}", openId, phoneNumber);
        } else {
            // 更新手机号信息
            user.setPhoneNumber(phoneNumber);
            user.setPurePhoneNumber(purePhoneNumber);
            user.setCountryCode(countryCode);
            xhsUserMapper.updateByPrimaryKey(user);
            log.info("更新小红书用户手机号: openId={}, phone={}", openId, phoneNumber);
        }
        return user;
    }
}
